import { defineComponent, onUnmounted, ref, watchEffect } from "vue";
import { clamp } from "./utils";

export const Hue = defineComponent({
    name: 'Hue',
    props: {
        value: {type: Object},
    },
    emits: ['change'],
    setup (props, {emit}) {
        const left = ref(clamp(props.value.hsl.h * 100 / 360, 0, 100));
        // const left = () => clamp(props.value.hsl.h * 100 / 360, 0, 100);
        let container: any;
        const handleMouseDown = (e: any) => {
            if (typeof e.button === 'number' && e.button !== 0) return false;
            handleChange(e);

            document.addEventListener('mousemove', handleChange, false);
            document.addEventListener('mouseup', onDragEnd, false);
        };

        const onDragEnd = (e: any) => {
            handleChange(e);
            document.removeEventListener('mousemove', handleChange);
            document.removeEventListener('mouseup', onDragEnd);
        };

        onUnmounted(() => {
            document.removeEventListener('mousemove', handleChange);
            document.removeEventListener('mouseup', onDragEnd);
        });

        const handleChange = (e: any) => {
            e.preventDefault();
            e.stopPropagation();

            const { clientWidth } = container;
            const xOffset = container.getBoundingClientRect().left + window.screenX;
            const left = e.clientX - xOffset;
            if (left < 0) {
                change(0);
                return;
            }
            if (left > clientWidth) {
                change(100);
                return;
            }


            change(left * 100 / clientWidth);
        };

        const change = (percent: number) => {
            left.value = clamp(percent, 0, 100);

            const {h, s, l, a} = props.value.hsl;
            const newHue = clamp(percent / 100 * 360, 0, 360);

            if (h !== newHue) {
                emit('change', {h: newHue, s, l, a, source: 'hsl'});
            }
        };

        watchEffect(() => {
            left.value = clamp(props.value.hsl.h * 100 / 360, 0, 100);
        });
        return () => <div class="cm-color-picker-hue" ref={(el) => container = el}>
            <div class="cm-color-picker-hue-wrap" onMousedown={handleMouseDown}>
                <div class="cm-color-picker-hue-pointer" style={{top: 0, left: `${left.value}%`}}></div>
            </div>
        </div>;
    }
});
